package com.je.meta.controller.upgrade;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.MetaService;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/je/meta/upgrade/version")
public class VersionController {

    @Autowired
    private MetaService metaService;

    /**
     * 列出所有增量升级包
     *
     * @param request
     * @return
     */
    @RequestMapping(value = {"/list"}, method = RequestMethod.GET, produces = "application/json; charset=utf-8")
    public BaseRespResult list(HttpServletRequest request) {
        String version = request.getParameter("version");
        if (Strings.isNullOrEmpty(version)) {
            return BaseRespResult.errorResult("版本号不能为空");
        }

        List<DynaBean> list = metaService.select("JE_META_UPGRADE_PRODUCT_VERSION",
                ConditionsWrapper.builder().eq("VERSION_BB", version));
        if (list == null || list.size() == 0) {
            return BaseRespResult.errorResult("没有找到版本信息");
        }

        List<Map<String, Object>> result = new ArrayList<>();
        Map<String, Object> eachMap;
        String eachFileArrayStr;
        JSONObject eachFileJson;
        for (DynaBean eachBean : list) {
            if ("JECLOUD_PLATFORM".equals(eachBean.getStr("VERSION_CPBM"))) {
                //平台升级包
                eachFileArrayStr = eachBean.getStr("VERSION_ZLSJB");
            }else {
                eachFileArrayStr = eachBean.getStr("VERSION_QLSJB");
            }
            if (Strings.isNullOrEmpty(eachFileArrayStr)) {
                continue;
            }

            eachFileJson = JSON.parseArray(eachFileArrayStr).getJSONObject(0);

            eachMap = new HashMap<>();
            eachMap.put("id", eachBean.get("JE_META_UPGRADE_PRODUCT_VERSION_ID"));
            eachMap.put("version", eachBean.get("VERSION_BB"));
            eachMap.put("name", eachFileJson.getString("relName"));
            eachMap.put("code", eachBean.getStr("VERSION_CPBM"));
            eachMap.put("file", eachFileJson.getString("fileKey"));
            result.add(eachMap);
        }
        return BaseRespResult.successResult(result);
    }


}
